import { NextRequest, NextResponse } from 'next/server';
import { GloableResponseItem, ResponseEnum } from '@/utils/request/res';
import { Auth, DbScheme, type ExtendedNextApiRequest, generateToken, hashPassword, LogOperation, ResponseHandler, verifyPassword, verifyToken } from '@/utils/decorator';
import prisma from '@/utils/db/PrismaService';

import { BaseController } from '@/utils/request/BaseController';
import { getCurrentTimeInShanghai } from '@/utils';
import { createDeptSchema, createDictSchema } from '@/dbSchema/systemSchema';
import { GET as HttpGet, POST as HttpPost, PUT as HttpPut, DELETE as HttpDelete } from '@/utils/decorator';
import { createAllMethodHandlers } from '@/utils/request/routeRegistry';
import { Prisma } from '@prisma/client';

const SYSTEM_DICT_TYPES = ['sys_user_role', 'sys_permission'];

class SystemDictController extends BaseController {
    // 新增字典
    @Auth()
    @ResponseHandler()
    @HttpPost()
    @DbScheme(createDictSchema)
    @LogOperation({
        module: "字典管理",
        operationName: "新增字典"
    })
    static async addDict(request: ExtendedNextApiRequest) {
        const {action,...data} = await request.customBody;
        data.create_time = getCurrentTimeInShanghai()
        data.update_time = getCurrentTimeInShanghai()
        if (request.user?.user_type !== "00") {
            return GloableResponseItem(ResponseEnum.fail, "只有超级管理员权限才可以创建", null)
        }
        try {
            const dict = await prisma.sysDict.findFirst({
                where: {
                    dict_id: data.dict_id,
                    dict_type: data.dict_type
                }
            })
            if (dict) {
                return GloableResponseItem(ResponseEnum.fail, "字典ID已存在", null)
            }
            await prisma.sysDict.create({
                data
            });
        } catch (error) {
            return GloableResponseItem(ResponseEnum.fail, "新增失败", null)
        }
        return GloableResponseItem(ResponseEnum.success, "新增成功", null)
    }

    // 获取字典
    @Auth()
    @ResponseHandler()
    @HttpGet()
    static async getDictList(request: ExtendedNextApiRequest) {
        const params: any = request.customBody
        const page = parseInt(params.page || '1');
        const pageSize = parseInt(params.pageSize || '10');
        const skip = (page - 1) * pageSize;

        const where: Prisma.SysDictWhereInput = {
            del_flag: 1,
            ...(params.dict_name && { dict_name: { contains: params.dict_name } }),
            ...(params.dict_type && { dict_type: { contains: params.dict_type } }),
        };

        try {
            const [data, total] = await prisma.$transaction([
                prisma.sysDict.findMany({
                    where,
                    orderBy: { create_time: 'desc' },
                    skip,
                    take: pageSize,
                }),
                prisma.sysDict.count({ where }),
            ]);

            const formatData = data.map(item => ({
                ...item,
                key: item.id
            }));

            return GloableResponseItem(ResponseEnum.success, "", {
                data: formatData || [],
                total: total,
                page,
                pageSize,
            });

        } catch (error) {
            console.log("error==========>>>>", error)
            return GloableResponseItem(ResponseEnum.fail, "获取失败", null)
        }
    }

    // 获取字典类型列表
    @Auth()
    @ResponseHandler()
    @HttpGet()
    static async getDictTypeList() {
        try {
            const dictTypes = await prisma.sysDict.findMany({
                where: {
                    del_flag: 1,
                },
                select: {
                    dict_type: true,
                },
                distinct: ['dict_type'],
            });

            return GloableResponseItem(ResponseEnum.success, "获取成功", dictTypes.map(d => d.dict_type));
        } catch (error) {
            console.error("获取字典类型列表失败:", error);
            return GloableResponseItem(ResponseEnum.fail, "获取失败", null);
        }
    }

    // 更新字典
    @Auth()
    @ResponseHandler()
    @HttpPut()
    @LogOperation({
        module: "字典管理",
        operationName: "更新字典"
    })
    static async updateDict(request: ExtendedNextApiRequest) {
        const {action,...data} = request.customBody;
        await createDictSchema.parse(data);
        data.update_time = getCurrentTimeInShanghai()
        await prisma.sysDict.update({
            where: { id: data.id },
            data
        });
        return GloableResponseItem(ResponseEnum.success, "修改成功", null)
    }

    // 删除字典
    @Auth()
    @ResponseHandler()
    @HttpDelete()
    @LogOperation({
        module: "字典管理",
        operationName: "删除字典"
    })
    static async deleteDict(request: ExtendedNextApiRequest) {
        const data = request.customBody;
        await prisma.sysDict.delete({
            where: { id: data.id }
        });
        return GloableResponseItem(ResponseEnum.success, "删除成功", null)
    }
}

// 使用自动路由处理器创建所有HTTP方法处理函数
const handlers = createAllMethodHandlers(SystemDictController);

export const { GET, POST, PUT, DELETE } = handlers;